<template>
    <el-dialog v-model="visible" title="修改膳食信息" width="500px" :close-on-click-modal="false" class="edit-meal-dialog">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="form-body">
            <el-form-item label="膳食ID">
                <el-input v-model="form.mealitemId" disabled />
            </el-form-item>

            <el-form-item label="膳食名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入膳食名称" />
            </el-form-item>

            <el-form-item label="描述" prop="description">
                <el-input v-model="form.description" placeholder="请输入描述" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                    <el-option label="启用" value="1" />
                    <el-option label="停用" value="0" />
                </el-select>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="submit">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineEmits } from 'vue'
import {inject} from 'vue'
const axios = inject("axios")
import { ElMessage } from 'element-plus'

const visible = ref(false)
const formRef = ref()
const form = ref({
    mealitemId: '',
    name: '',
    description: '',
    status: '1'
})
const emit = defineEmits(['success'])

const rules = {
    name: [{ required: true, message: '请输入膳食名称', trigger: 'blur' }],
    description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const open = (row) => {
    form.value = { ...row }
    visible.value = true
}

const submit = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.warning('请填写所有必填字段')
            return
        }

        try {
            const res = await axios.post('/mealitem/updateMealitem', null, {
                params: form.value
            })
            if (res.data.status === 200) {
                ElMessage.success('修改成功')
                visible.value = false
                emit('success')
            } else {
                throw new Error(res.data.msg)
            }
        } catch (err) {
            ElMessage.error('修改失败：' + err.message)
        }
    })
}

defineExpose({ open })
</script>

<style scoped>
.edit-meal-dialog ::v-deep(.el-dialog__header) {
    padding-bottom: 10px;
}

.form-body {
    padding: 10px 0;
}

.el-form-item {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 10px;
}

.el-input,
.el-select {
    width: 100%;
}
</style>
